package com.zlm.common.util;

import com.zlm.common.enums.UncommonCharacterEnum;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: duyufu
 * @Date: 2019/5/6 15:16
 */
public class PinyinUtils {

    private static final String[] uncommonCharacterArr = {"凃","庒","囖"};

    /**
     * 汉字获取拼音首字母大写，英文忽略
     * @param str
     * @return
     */
    public static String getFirstLetter(String str) {
        StringBuffer pybf = new StringBuffer();
        try {
            if(StringUtils.isBlank(str)){
                return "";
            }
            char[] arr = str.toCharArray();
            HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
            format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
            format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            if(arr[0]>128) {
                try {
                    List<String> uncommonCharacterList = Arrays.asList(uncommonCharacterArr);
                    if(uncommonCharacterList.contains(String.valueOf(arr[0]))){
                        return UncommonCharacterEnum.getNameByCode(String.valueOf(arr[0]));
                    }
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[0], format);
                    if (temp != null) {
                        pybf.append(temp[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(arr[0]);
            }
            return pybf.toString().toUpperCase();
        } catch (Exception e) {
            return pybf.append("#").toString();
        }
    }
}
